package com.example.administrator.printoutindemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.printoutindemo.services.Tools;
import com.example.administrator.printoutindemo.view.MyImageButton;
import com.example.administrator.printoutindemo.zxing.activity.CaptureActivity;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.zhinenghuacangku.mvp.ui.activity.ScanQRCodeActivity;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import com.jess.arms.base.BaseConstants;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;


public class StoreSGJLCutMidQRC extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    private static final String WEBSERVICE_CONFIG = "TEXT";
    private static final String TAG = "GPS Services";
    private static final int STOP = 0;
    private static final int THREADING = 1;
    private static final int SUBMITSUCCESS = 2;
    private static final int SUBMITUNSUCESS = 3;
    private static final int NO_DATA = 5;
    public LocationManager lm;
    ImageView mBtnRight;
    private MyImageButton store_btn_QRCode = null;
    private TextView s_qrc_projectname = null;
    private TextView s_qrc_material = null;
    private TextView s_qrc_fmmaterial = null;
    private EditText s_qrc_submitQuestion = null;
    private Button s_qrc_btn_submit = null;
    private Button s_qrc_btn_editmaterialnum = null;
    private OutStorageDetail outstoragedetail = null;
    private List<OutStorageDetail> li_outdetail = new ArrayList<>();
    private String scanResult = "";
    private TextView s_qrc_readdress = null;
    private TextView s_qrc_reusername = null;
    private TextView s_qrc_rephone = null;
    @SuppressLint("HandlerLeak")
    Handler hanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STOP:

                    if (li_outdetail.size() == 1) {
                        OutStorageDetail in = li_outdetail.get(0);

                        String projectname = Tools.ToDBC(Tools.stringFilter(in
                                .get_projectname()));
                        String material = Tools.ToDBC(Tools.stringFilter(in
                                .get_material()));
                        String fmmaterial = Tools.ToDBC(Tools.stringFilter(in
                                .get_fmmaterial()));
                        String readdress = Tools.ToDBC(Tools.stringFilter(in
                                .get_receive_address()));
                        String reusername = Tools.ToDBC(Tools.stringFilter(in
                                .get_receive_userName()));
                        String rephone = Tools.ToDBC(Tools.stringFilter(in
                                .get_receive_userPhone()));


                        s_qrc_projectname.setText(projectname);
                        s_qrc_material.setText(material);
                        s_qrc_fmmaterial.setText(fmmaterial);
                        s_qrc_readdress.setText(readdress);
                        s_qrc_reusername.setText(reusername);
                        s_qrc_rephone.setText(rephone);


                    }

                    LoadingDialogUtil.dismissDialog();
                    break;

                case THREADING:

                    LoadingDialogUtil.dismissDialog();

                    break;

                case SUBMITSUCCESS:
                    s_qrc_btn_submit.setVisibility(View.GONE);
                    Toast.makeText(StoreSGJLCutMidQRC.this, "提交数据成功！",
                            Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();

                    break;

                case SUBMITUNSUCESS:
                    Toast.makeText(StoreSGJLCutMidQRC.this, "提交数据失败！",
                            Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();

                    break;
                case NO_DATA:
                    ArmsUtils.makeText(StoreSGJLCutMidQRC.this, "二维码错误,没有查询到相关数据");
                    break;
            }

        }
    };
    private TextView s_gps_mjd;
    private TextView s_gps_mwd;
    private TextView s_gps_num;
    // 状态监听
    GpsStatus.Listener listener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) {
            switch (event) {
                // 第一次定位
                case GpsStatus.GPS_EVENT_FIRST_FIX:
//                    Log.i(TAG, "第一次定位");
                    break;
                // 卫星状态改变
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
//                    Log.i(TAG, "卫星状态改变");
                    // 获取当前状态
                    if (ActivityCompat.checkSelfPermission(StoreSGJLCutMidQRC.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    GpsStatus gpsStatus = lm.getGpsStatus(null);
                    // 获取卫星颗数的默认最大值
                    int maxSatellites = gpsStatus.getMaxSatellites();
                    // 创建一个迭代器保存所有卫星
                    Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
                            .iterator();
                    int count = 0;
                    while (iters.hasNext() && count <= maxSatellites) {
                        GpsSatellite s = iters.next();
                        count++;
                    }
                    // System.out.println("搜索到：" + count + "颗卫星");
                    s_gps_num.setText("搜索到：" + count + "颗卫星");
                    break;
                // 定位启动
                case GpsStatus.GPS_EVENT_STARTED:
                    Log.i(TAG, "定位启动");
                    break;
                // 定位结束
                case GpsStatus.GPS_EVENT_STOPPED:
                    Log.i(TAG, "定位结束");
                    break;

            }
        }

        ;
    };
    private GPSLocation gpsLocation = new GPSLocation();
    private GpsInfo gpsInfo = null;
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    // 位置监听
    private LocationListener locationListener = new LocationListener() {

        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {
            updateView(location);
            Log.i(TAG, "时间：" + location.getTime());
            Log.i(TAG, "经度：" + location.getLongitude());
            Log.i(TAG, "纬度：" + location.getLatitude());
            Log.i(TAG, "海拔：" + location.getAltitude());
        }

        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                // GPS状态为可见时
                case LocationProvider.AVAILABLE:
//                    Log.i(TAG, "当前GPS状态为可见状态");
                    break;
                // GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
//                    Log.i(TAG, "当前GPS状态为服务区外状态");
                    break;
                // GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
//                    Log.i(TAG, "当前GPS状态为暂停服务状态");
                    break;
            }
        }

        /**
         * GPS开启时触发
         */
        public void onProviderEnabled(String provider) {
            if (ActivityCompat.checkSelfPermission(StoreSGJLCutMidQRC.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(StoreSGJLCutMidQRC.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Location location = lm.getLastKnownLocation(provider);
            updateView(location);
        }

        /**
         * GPS禁用时触发
         */
        public void onProviderDisabled(String provider) {
            updateView(null);
        }
    };
    private SharedPreferences sPreferencces;
    private View.OnClickListener mRightListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getPermission()) {

                toScanQRCodeActivity();
            }
        }
    };

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store_activity_sgjl_qrcode);
        sPreferencces = getSharedPreferences(WEBSERVICE_CONFIG, 0);
        ToolbarUtils.initToolbarTitleBack(this, "施工监理");

        mBtnRight = findViewById(R.id.btnRight);
        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_scan));
        mBtnRight.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getPermission()) {
                    li_outdetail.clear();
                    toScanQRCodeActivity();
                }
            }
        });
        store_btn_QRCode = (MyImageButton) findViewById(R.id.store_btn_QRCode);
        s_qrc_projectname = (TextView) findViewById(R.id.s_qrc_projectname);
        s_qrc_material = (TextView) findViewById(R.id.s_qrc_material);
        s_qrc_fmmaterial = (TextView) findViewById(R.id.s_qrc_fmmaterial);
        s_qrc_submitQuestion = (EditText) findViewById(R.id.s_qrc_submitQuestion);
        s_qrc_btn_submit = (Button) findViewById(R.id.s_qrc_btn_submit);
        s_qrc_btn_editmaterialnum = (Button) findViewById(R.id.s_qrc_btn_editmaterialnum);

        s_qrc_readdress = (TextView) findViewById(R.id.s_qrc_readdress);
        s_qrc_reusername = (TextView) findViewById(R.id.s_qrc_reusername);
        s_qrc_rephone = (TextView) findViewById(R.id.s_qrc_rephone);

        gpsInfo = new GpsInfo();
        s_gps_mjd = (TextView) findViewById(R.id.s_gps_mjd);
        s_gps_mwd = (TextView) findViewById(R.id.s_gps_mwd);
        s_gps_num = (TextView) findViewById(R.id.s_gps_num);

        outstoragedetail = new OutStorageDetail(this);

        store_btn_QRCode.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 扫码
                s_qrc_btn_submit.setVisibility(View.VISIBLE);
                Intent openCameraIntent = new Intent(StoreSGJLCutMidQRC.this,
                        CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
            }
        });

        s_qrc_btn_editmaterialnum.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (li_outdetail.size() == 1) {
                    OutStorageDetail in = li_outdetail.get(0);

                    // 跳转物料修改页面
                    Intent listIntent1 = new Intent();

                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为tinyphp
                    bundle.putSerializable("OutStorageDetail", in);
                    listIntent1.putExtras(bundle);

                    listIntent1.setClass(StoreSGJLCutMidQRC.this,
                            StoreSGJLEditMaterialNums.class);
                    startActivity(listIntent1);
                } else {
                    ArmsUtils.makeText(StoreSGJLCutMidQRC.this, "请先扫描物料二维码");
                    return;
                }


            }
        });

        registerGPS();// 在这里获取gps信息，更新到textview里

        s_qrc_btn_submit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 提交

                if (!scanResult.equals("")) {

                    LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);

                    new Thread(new Runnable() {

                        @Override
                        public void run() {

                            SimpleDateFormat df = new SimpleDateFormat(
                                    "yyyy-MM-dd HH:mm:ss");// 设置日期格式
                            String submitTime = df.format(new Date());

                            OutStorageDetail o = li_outdetail.get(0);

                            int checkUid = Integer.parseInt(o.get_op_uid());

                            o.set_jd(s_gps_mjd.getText().toString());
                            o.set_wd(s_gps_mwd.getText().toString());
                            o.set_remark(s_qrc_submitQuestion.getText().toString());


                            String re = UploadOutDetail(o);

                            if (re.equals("1")) {
                                Message m = new Message();
                                m.what = StoreSGJLCutMidQRC.SUBMITSUCCESS;
                                hanlder.sendMessage(m);

                            } else {
                                Message m = new Message();
                                m.what = StoreSGJLCutMidQRC.SUBMITUNSUCESS;
                                hanlder.sendMessage(m);
                            }

                        }
                    }).start();

                }

            }
        });
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的照相使用权限", 103, permissions);
            return false;
        }

    }

    private void toScanQRCodeActivity() {
        Intent newIntent = new Intent(this, ScanQRCodeActivity.class);
        SharedPreferences.Editor editor = sPreferencces.edit();
        editor.putInt(SCAN_REQUEST_CODE, 101);
        editor.commit();
        // 开始一个新的 Activity等候返回结果
        startActivityForResult(newIntent, 101);
    }

    private void registerGPS() {
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // 判断GPS是否正常启动
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();
            // 返回开启GPS导航设置界面
            // Intent intent = new
            // Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            // startActivityForResult(intent, 0);
            return;
        }

        // 为获取地理位置信息时设置查询条件
        String bestProvider = lm.getBestProvider(getCriteria(), true);
        // 获取位置信息
        // 如果不设置查询要求，getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = lm.getLastKnownLocation(bestProvider);
        // Location location=
        // lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        updateView(location);
        // 监听状态
        lm.addGpsStatusListener(listener);
        // 绑定监听，有4个参数
        // 参数1，设备：有GPS_PROVIDER和NETWORK_PROVIDER两种
        // 参数2，位置信息更新周期，单位毫秒
        // 参数3，位置变化最小距离：当位置距离变化超过此值时，将更新位置信息
        // 参数4，监听
        // 备注：参数2和3，如果参数3不为0，则以参数3为准；参数3为0，则通过时间来定时更新；两者为0，则随时刷新

        // 1秒更新一次，或最小位移变化超过1米更新一次；
        // 注意：此处更新准确度非常低，推荐在service里面启动一个Thread，在run中sleep(10000);然后执行handler.sendMessage(),更新位置
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
                locationListener);
        // lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1,
        // locationListener);
    }

    // 上传经度纬度及反馈问题
    private String UploadOutDetail(
            OutStorageDetail outDetailJsonStr) {

        String result = "0";

        String jsonStr = outstoragedetail
                .ConvertToJson(outDetailJsonStr);
        try {
            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "UpdateSGJL";

            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreCutMidServivce.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("modelJson", jsonStr);
            // request.addProperty("pass", edtPwd.getText().toString());
            // request.addProperty("sYardCode", "WLY");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                String returnStr = response.toString();

                result = returnStr;

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 返回查询条件
     *
     * @return
     */
    private Criteria getCriteria() {
        Criteria criteria = new Criteria();
        // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        // 设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费
        criteria.setCostAllowed(false);
        // 设置是否需要方位信息
        criteria.setBearingRequired(false);
        // 设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }

    /**
     * 实时更新文本内容
     *
     * @param location
     */
    private void updateView(Location location) {

        if (location != null) {
            s_gps_mjd.setText(String.valueOf(location.getLongitude()));
            s_gps_mwd.setText(String.valueOf(location.getLatitude()));
            gpsLocation.setLongitude(String.valueOf(location.getLongitude()));// 经度
            gpsLocation.setLatitude(String.valueOf(location.getLatitude()));// 维度
        } else {
            s_gps_mjd.setText("-");
            s_gps_mwd.setText("-");
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
//
//        if (resultCode == RESULT_OK) {
//            Bundle bundle = data.getExtras();
//            scanResult = bundle.getString("result");
//            // lbl_QRCode.setText(scanResult);
//
//
//
//            new Thread() {
//                @Override
//                public void run() {
//                    li_outdetail = GetOutStorageDetailFromWebService(scanResult);
//
//                    if (li_outdetail.size() == 1) {
//
//                        OutStorageDetail o = li_outdetail.get(0);
//
//                        Message m = new Message();
//                        m.what = StoreSGJLCutMidQRC.STOP;
//                        hanlder.sendMessage(m);
//                    }
//                }
//            }.start();
//
//        }

        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);

                Bundle bundle = data.getExtras();
                scanResult = bundle.getString("scan_result");
                // lbl_QRCode.setText(scanResult);


                new Thread() {
                    @Override
                    public void run() {
                        List<OutStorageDetail> outStorageDetailList = GetOutStorageDetailFromWebService(scanResult);
                        if (outStorageDetailList != null && outStorageDetailList.size() > 0) {

                            li_outdetail.addAll(outStorageDetailList);
//                        li_outdetail = GetOutStorageDetailFromWebService(scanResult);

                            if (li_outdetail.size() == 1) {

                                OutStorageDetail o = li_outdetail.get(0);

                                Message m = new Message();
                                m.what = StoreSGJLCutMidQRC.STOP;
                                hanlder.sendMessage(m);
                            }
                        } else {
                            Message m = new Message();
                            m.what = StoreSGJLCutMidQRC.NO_DATA;
                            hanlder.sendMessage(m);
                        }
                    }
                }.start();
            }

        }
    }

    // 获取基本信息  162
    private List<OutStorageDetail> GetOutStorageDetailFromWebService(
            String out_storage_detail_Id) {

        List<OutStorageDetail> list = null;
        try {
            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "GetListOutStorageByQRCodeCutMid";


            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreCutMidServivce.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("out_storage_detail_Id", out_storage_detail_Id);
            // request.addProperty("pass", edtPwd.getText().toString());
            // request.addProperty("sYardCode", "WLY");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                String returnStr = response.toString();

                if ("" != returnStr) {
                    returnStr = returnStr.substring(returnStr.lastIndexOf("["),
                            returnStr.length());

                    returnStr = returnStr.replace("\\", "");

                    if (!returnStr.equals("[]")) {
                        list = outstoragedetail.getListFromJSON(returnStr);
                    }

                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

}